import 'package:flutter/material.dart';
import 'package:shortmovieapp/Common.dart';
import 'package:shortmovieapp/data/viewData.dart';
import 'package:shortmovieapp/myController/RequestServerController.dart';
import 'package:shortmovieapp/myController/appController.dart';
import 'shareView.dart';

class recommendedPage extends StatefulWidget{
  //late List<TypeMovieItems>? recommendedPageData;
  static List<MovieType> s_recommendedTitles = MovieType.values;
  
  List<MovieType> get recommendedTitles  =>s_recommendedTitles;

  recommendedPage({super.key});

  @override
  State<recommendedPage> createState() => _recommendedPageState();
}

class _recommendedPageState extends State<recommendedPage>
    with SingleTickerProviderStateMixin {
  late TabController? _tabController;

  int _currentTabIndex = 0;

  @override
  void dispose() {
    super.dispose();

    _tabController?.dispose();
  }

  @override
  void initState() {
    super.initState();

    Debug.log("recommendedPage init state ${appController().recommendedPageData}");

    initTabController();

     if (appController().recommendedPageData == null ||
         appController().recommendedPageData!.length <= 0 ||
         appController().recommendedPageData![0].itemDatas.length <= 0
         )
         requestRemoteItems();
  }

  void initTabController() {
    _tabController = TabController(
        initialIndex: _currentTabIndex,
        length: widget.recommendedTitles!.length,
        animationDuration: const Duration(milliseconds: 200),
        vsync: this);
  }

  void requestRemoteItems() async{
    Debug.log("RequestRemoteItems");
    List<TypeMovieItems> data = await RequestServerController()
           .getRecommendedMoviesData(widget.recommendedTitles);
   
    Future(() {
          setState(() {
       Debug.log("RequestRemoteItems end:${data?.length}");
       appController().recommendedPageData = data;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    if (appController().recommendedPageData == null
    || appController().recommendedPageData!.isEmpty) {
      Debug.log("items data is null ,waiting for fetch remnote data");
      return Container();
    }

    Debug.log("items data length:${appController().recommendedPageData?.length}");
    return
     Container(
      padding: const EdgeInsets.fromLTRB(10, 30, 10, 0),
      alignment: Alignment.center,
      child: tabBarView(
        widget.recommendedTitles,
        appController().recommendedPageData!,
        context,
        _tabController,
        (value) {
          Debug.log("tabBar tap: $value");
          setState(() {
            _currentTabIndex = value;
          });
        },
      ),
    );
  }
}

//顶部条
AppBar topBar(BuildContext context) {
  return AppBar(
      //backgroundColor: Colors.red,
      leading: Container(
          width: 100,
          height: double.maxFinite,
          alignment: Alignment.center,
          child: const Text(
            "推荐",
            style: TextStyle(fontSize: 18, color: Colors.white),
          )),
      actions: [
        Container(
            width: 100,
            height: double.maxFinite,
            alignment: Alignment.centerRight,
            child: IconButton(
              onPressed: () {
                Debug.log("on click search");
                Navigator.of(context).pushNamed("/search");
              },
              icon: const Icon(Icons.search),
            ))
      ]);
}

Tab topTab(String title) {
  return Tab(text: title);
}

//推荐内容，根据分类显示列表
Widget tabBarView(
    List<MovieType> typeTitles,
    List<TypeMovieItems> typeItemsList,
    BuildContext context,
    TabController? tabController,
    Function(int)? onTabTap) {
  Debug.log("tabBarView init");

  return Scaffold(
    //backgroundColor: Colors.white,
    appBar: PreferredSize(
      preferredSize: const Size.fromHeight(80),
      child: AppBar(
        leading: Container(
            width: 100,
            height: double.maxFinite,
            alignment: Alignment.center,
            child: const Text(
              "推荐",
              style: TextStyle(fontSize: 18, color: Colors.white),
            )),
        actions: [
          searchButton(size: 50,alignment: Alignment.centerRight,onClick: ()=>Navigator.of(context).pushNamed(MyPageRoute.seach),)
        ],
        backgroundColor: Colors.transparent,
        bottom: TabBar(
          tabAlignment: TabAlignment.start,
          isScrollable: true,
          controller: tabController,
          onTap: onTabTap,
          tabs: typeTitles.map((e) => topTab(MovieType2String(e))).toList(),
        ),
      ),
    ),
    body: TabBarView(
      controller: tabController,
      children: typeItemsList
          .map((e) => MovieItemsGrid(itemDatas: e.itemDatas))
          .toList(),
    ),
  );
}
